package com.ztesoft.zsmart.zcm.monitor.utils;

import com.alibaba.fastjson.JSONObject;
import com.ztesoft.zsmart.core.exception.BaseAppException;
import com.ztesoft.zsmart.core.log.ZSmartLogger;
import com.ztesoft.zsmart.zcm.core.remote.RestClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

public final class RestRequestHelper {
    private static final ZSmartLogger LOGGER = ZSmartLogger.getLogger(RestRequestHelper.class);

    private static RestClient restClient;

    private RestRequestHelper() {

    }

    public static String request(String url, JSONObject requestJsonParam) throws BaseAppException {
        String response = null;
        HttpHeaders headers = getRequestHeader();
        HttpEntity<String> formEntity = new HttpEntity<String>(requestJsonParam.toJSONString(), headers);
        try {
            LOGGER.debug("url is [{}], request param [{}]", url, requestJsonParam.toJSONString());
            if (restClient == null) {
                restClient = SpringContextUtil.getBean(RestClient.class);
            }
            response = restClient.postForObject(url, formEntity, String.class);
            LOGGER.info("Request end, response is {}", response);
        }
        catch (Exception e) {
            LOGGER.error(e);
        }
        return response;
    }

    private static HttpHeaders getRequestHeader() {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        return headers;
    }
}
